package cn.bytecollege.admin.filter;

import cn.bytecollege.common.constant.Resource;
import com.google.code.kaptcha.Constants;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebFilter(filterName = "AdminRegisterFilter",servletNames = "AdminRegisterController")
public class AdminRegisterFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String method = req.getMethod();

        if(method.equalsIgnoreCase("post")){
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String name = request.getParameter("name");
            String msg = null;

            Pattern usernamePattern = Pattern.compile("\\w{5,12}");
            Matcher usernameMatcher = usernamePattern.matcher(username);
            if (!usernameMatcher.matches()){
                //账号不合法
                msg = "请重新输入,账号格式为5到12位的数字，字母，下划线";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/reg.jsp").forward(request,response);
                return;
            }
            Pattern passwordPattern = Pattern.compile("\\d{4,12}");
            Matcher passwordMatcher = passwordPattern.matcher(password);
            if (!passwordMatcher.matches()){
                //密码不合法
                msg = "请重新输入,密码格式为4到12位的数字";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/reg.jsp").forward(request,response);
                return;
            }
            Pattern namePattern = Pattern.compile("^(?!_)(?!.*?_$)[a-zA-Z0-9_\\u4e00-\\u9fa5]+$");
            Matcher nameMatcher = namePattern.matcher(name);
            if (!nameMatcher.matches()){
                msg = "姓名格式不正确，格式为数字、字母、下划线、中文且不能以下划线开始或者结束";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/reg.jsp").forward(request,response);
                return;
            }
            chain.doFilter(request,response);
        }else {
            chain.doFilter(request, response);
        }
    }
}
